package com.gws.juc;

import java.util.concurrent.ExecutionException;
import java.util.concurrent.ForkJoinPool;
import java.util.concurrent.ForkJoinTask;
import java.util.concurrent.RecursiveTask;

class MyTask extends RecursiveTask<Integer>{
	private static final Integer ADJUST_VALUE = 10;
	
	private int begin;
	private int end;
	private int result;
	
	
	public MyTask(int begin, int end) {
		super();
		this.begin = begin;
		this.end = end;
	}

	@Override
	protected Integer compute() {
		if((end - begin) < ADJUST_VALUE){
			for (int i = begin; i <= end; i++) {
				result = result + i;
			}
		}else{
			int middle = (begin + end)/2;
			MyTask mytask1 = new MyTask(begin, middle);
			MyTask mytask2 = new MyTask(middle+1, end);
			mytask1.fork();
			mytask2.fork();
			result = mytask1.join() + mytask2.join();
			
		}
		return result;
	}
}

/**
 * 分支合并框架
 * @author gws
 *
 */
public class ForkJoinDemo {
	public static void main(String[] args) throws Exception, ExecutionException {
		
		MyTask myTask = new MyTask(0, 100000);
		ForkJoinPool threadPool = new ForkJoinPool();
		ForkJoinTask<Integer> forkJoinTask = threadPool.submit(myTask);
		System.out.println(forkJoinTask.get());
		threadPool.shutdown();
	}

}
